"""
统一内容处理器 - 消除所有重复的内容类型检测
基于Linus设计哲学："好代码没有特殊情况"
"""

from typing import Any, Dict, Optional
from .json_utils import json_dumps


class ContentProcessor:
    """统一内容处理器 - 消除所有重复的内容类型检测"""
    
    @staticmethod
    def detect_content_type(content: Any) -> str:
        """智能检测内容类型"""
        if isinstance(content, bytes):
            return "application/octet-stream"
        elif isinstance(content, dict):
            return "application/json; charset=utf-8"
        elif isinstance(content, str):
            return "text/html; charset=utf-8" if "<" in content else "text/plain; charset=utf-8"
        else:
            return "text/plain; charset=utf-8"
    
    @staticmethod
    def process_content(content: Any) -> bytes:
        """统一内容处理为bytes"""
        if isinstance(content, bytes):
            return content
        elif isinstance(content, dict):
            return json_dumps(content).encode('utf-8')
        else:
            return str(content).encode('utf-8')
    
    @staticmethod
    def prepare_headers(content: Any, custom_headers: Optional[Dict[str, str]] = None) -> Dict[str, str]:
        """准备完整的响应头部"""
        headers = custom_headers or {}
        content_type = ContentProcessor.detect_content_type(content)
        headers.setdefault("content-type", content_type)
        
        # 确保所有header值都是字符串 - 消除encode()错误
        for key, value in headers.items():
            if not isinstance(value, str):
                headers[key] = str(value)
        
        return headers


# 极简响应函数 - 一行解决所有响应
def respond(content: Any, status: int = 200, **headers):
    """统一响应函数 - 自动检测内容类型"""
    from .response import Response
    return Response(content, status, headers)


# 便捷别名 - 保持API简洁
json = respond
html = respond
text = respond

def error(msg: Any, status: int = 400):
    """错误响应 - 自动包装为错误格式"""
    if isinstance(msg, str):
        msg = {"error": msg}
    return respond(msg, status)